<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Payment" and licensed under
// the terms of the GNU Affero General Public License version 3, or (at your
// option) a later version. You should have received a copy of this license
// along with the software. If not, see <https://www.gnu.org/licenses/>.

namespace Hawese\Payment\Gateways;

use Hawese\Payment\Support\Http as HttpSupport;
use Psr\Http\Message\RequestInterface;

class KhipuRequestBuilder extends AbstractRequestBuilder
{
    const ENDPOINT = 'https://khipu.com/api/2.0';

    private $credentials;

    public function __construct(...$args)
    {
        parent::__construct(...$args);
        $this->credentials = (object) config('gateways.khipu.credentials');
        $this->addDefaultHeaders();
    }

    protected function getEndpoint(): string
    {
        return self::ENDPOINT;
    }

    private function addDefaultHeaders(): void
    {
        $this->headers['Authorization'] = $this->authorizationHeader();
    }

    private function authorizationHeader(): string
    {
        return $this->credentials->receiverId . ':' . $this->getSignature();
    }

    private function getSignature(): string
    {
        return hash_hmac(
            'sha256',
            $this->toSign(),
            $this->credentials->secretKey
        );
    }

    private function toSign(): string
    {
        $params = $this->getBodyOrQueryParams();
        ksort($params); // Khipu signature requires sorting

        return $this->method . '&' .
            rawurlencode((string) $this->buildUri()->withQuery('')) . '&' .
            HttpSupport::buildUriQuery($params);
    }
}
